<?php
namespace com\rs\dns\filter;

use com\rs\dns\constant\ApiConstant;
use com\rs\dns\constant\ConfigConstant;
use com\rs\dns\exception\BaException;
use com\rs\dns\service\ConfigService;
use com\rs\dns\service\TokenService;
use com\rs\dns\service\user\impl\UserServiceImpl;
use com\rs\dns\service\user\impl\UserSessionServiceImpl;
use restphp\http\RestHttpRequest;
use restphp\utils\RestStringUtils;

/**
 * Class IFrameApiFilter
 * @package com\rs\dns\filter
 */
final class IFrameApiFilter {
    private static $_isIFrameApi = 'N';
    private static $_token = "";
    /**
     * 过滤器入口.
     * @throws BaException
     * @throws \restphp\exception\RestException
     */
    public static function run() {
        $iframeToken = RestHttpRequest::getGet("iframe-token");
        if (RestStringUtils::isBlank($iframeToken)) {
            //如果没有值，则认为是非IFrame API引用
            return;
        }

        self::$_isIFrameApi = 'Y';

        //检查接口是否开启
        if (!self::isOpen()) {
            throw new BaException(ApiConstant::IFRAME_API_CLOSED);
        }

        //获取token完整信息
        $tokenBean = TokenService::getBeanByToken($iframeToken);
        if (null == $tokenBean) {
            throw new BaException(ApiConstant::IFRAME_API_TOKEN_ERROR);
        }

        //过期检查
        if (strtotime($tokenBean->getExpireAt()) < time()) {
            //先清除过期token
            TokenService::deleteByToken($iframeToken);

            throw new BaException(ApiConstant::IFRAME_API_TOKEN_EXPIRED);
        }

        //获取用户信息
        $userService = new UserServiceImpl();
        $user = $userService->getInfo($tokenBean->getUserId());
        if (null == $user) {
            //先清除错误token
            TokenService::deleteByToken($iframeToken);
            throw new BaException(ApiConstant::IFRAME_API_TOKEN_ERROR);
        }

        //token续期
        self::$_token = $iframeToken;
        TokenService::renewal($iframeToken);

        //设置登录状态
        $userSessionService = new UserSessionServiceImpl();
        $userSessionService->makeSession($user);
    }

    /**
     * 是否是IFrame API访问.
     * @return bool
     */
    public static function isIFrameApi() {
        $isIFrameApi = 'Y' == self::$_isIFrameApi;
        if ($isIFrameApi) {
            TokenService::renewal(self::$_token);
        }
        return $isIFrameApi;
    }

    /**
     * 获取Token.
     * @return string
     */
    public static function getToken() {
        return self::$_token;
    }

    /**
     * 是否开启API.
     * @return bool
     * @throws \restphp\exception\RestException
     */
    private static function isOpen() {
        $allow = ConfigService::getConfigValue(ConfigConstant::CODE_ALLOW_IFRAME_API);
        return "Y" == $allow;
    }

}